//
//  UIImage+Extend.m
//  ReviewDemo
//
//  Created by 龙 on 2018/3/16.
//  Copyright © 2018年 long. All rights reserved.
//

#import "UIImage+Extend.h"
#import <objc/runtime.h>

@implementation UIImage (Extend)

+ (void)load
{
    Method oldImageName = class_getClassMethod(self, @selector(imageNamed:));
    Method newImageName = class_getClassMethod(self, @selector(tip_ImageNamed:));
    method_exchangeImplementations(oldImageName, newImageName);
}


//不能在分类中重写系统方法imageNamed，因为会把系统的功能给覆盖掉，而且分类中不能调用super
+ (UIImage *)tip_ImageNamed:(NSString *)name
{
    UIImage *image = [UIImage tip_ImageNamed:name];
    if (image)
    {
        NSLog(@"加载图片成功");
    }
    else
    {
        NSLog(@"加载图片失败");
    }
    return image;
}

+ (UIImage*)createImageWithColor:(UIColor*)color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}



- (UIImage *)imageByScalingToSize:(CGSize)targetSize
{
    UIImage *sourceImage =self;
    UIImage *newImage =nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor =0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if(CGSizeEqualToSize(imageSize, targetSize) ==NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor < heightFactor) scaleFactor = widthFactor;
        else scaleFactor = heightFactor; scaledWidth= width * scaleFactor;
        scaledHeight = height * scaleFactor;
        // center the image
        if(widthFactor < heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) *0.5;
            
        }
        else if(widthFactor > heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) *0.5;
            
        }
    }
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(targetSize);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if(newImage ==nil)
        NSLog(@"could not scale image");
    return newImage ;
}

@end
